//把一个数组最开始的若干个元素搬到数组的末尾，我们称之为数组的旋转。输入一个递增排序的数组的一个旋转，输出旋转数组的最小元素。例如，数组 [3,4,5,1,2
//] 为 [1,2,3,4,5] 的一个旋转，该数组的最小值为1。 
//
// 示例 1： 
//
// 输入：[3,4,5,1,2]
//输出：1
// 
//
// 示例 2： 
//
// 输入：[2,2,2,0,1]
//输出：0
// 
//
// 注意：本题与主站 154 题相同：https://leetcode-cn.com/problems/find-minimum-in-rotated-sor
//ted-array-ii/ 
// Related Topics 数组 二分查找 
// 👍 373 👎 0


package leetcode.editor.cn1;

/**
 * 二分查找
 */
public class XuanZhuanShuZuDeZuiXiaoShuZiLcof_2 {
    public static void main(String[] args) {
        Solution solution = new XuanZhuanShuZuDeZuiXiaoShuZiLcof_2().new Solution();
        // TO TEST
//        System.out.println(solution.minArray(new int[]{10, 1, 10, 10, 10}));
//        System.out.println(solution.minArray(new int[]{3, 4, 5, 1, 2}));
//        System.out.println(solution.minArray(new int[]{2, 2, 2, 0, 1}));
//        System.out.println(solution.minArray(new int[]{3, 1, 1}));
        System.out.println(solution.minArray(new int[]{1,1,3,1}));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int minArray(int[] numbers) {
            if (numbers.length == 0)
                return -1;
            if (numbers.length == 1)
                return numbers[0];
            int i = 0, j = numbers.length - 1, mid;
            int nlen = numbers.length;
            int min = Integer.MAX_VALUE;
            if (numbers[i] < numbers[j])
                return numbers[0];
            // 结束条件
            while (numbers[i] >= numbers[j]) {
                if (j - i == 1) {
                    return numbers[j];
                }
                mid = (i + j) / 2;
                if (numbers[i] == numbers[mid] && numbers[j] == numbers[mid]) {
                    // 只能 顺序查找
                    for (int i1 = 0; i1 < nlen; i1++) {
                        if (min > numbers[i1]) {
                            min = numbers[i1];
                        }
                    }
                    return min;
                }
                if (numbers[mid] >= numbers[i]) {
                    i = mid;
                } else if (numbers[mid] <= numbers[j]) {
                    j = mid;
                }
            }
            return min;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
